<template>
  <div>
	<Tabs v-model='tabsValue' capture-focus>
		<TabPane label="基本信息" name="basic">
			<Card :bordered="false">
				<p slot="title">商品概要</p>
				<Form ref="formBasic" :model="formData" :rules="ruleBasicValidate" :label-width="120">
					<FormItem prop="title" label="名称" >
						<Input v-model="formData.title" style="width: 400px;"></Input>
					</FormItem>
					<FormItem prop="subTitle" label="副标题" >
						<Input v-model="formData.subTitle" placeholder="(选填)网页中显示在名称下方" style="width: 400px;"></Input>
					</FormItem>
					<FormItem label="分类" prop="catalogIDs">
						<Cascader :data="queryCatalogData" style="width: 200px;" @on-visible-change='onVisibleChange'
						:load-data="loadCatalogData" @on-change='onCatalogChange' v-model="formData.catalogIDs">
						</Cascader>
					</FormItem>
					<FormItem label="品牌" >
						<Select v-model="formData.brand" style="width: 200px;">
							<Option v-for="brand in brandData" :key="brand.id" :value="brand.id">{{brand.cname}}</Option>
						</Select>
					</FormItem>
					<FormItem label="售价" prop="price" >
						<InputNumber  :min="0" v-model="formData.price"  style="width: 200px;"></InputNumber> 元
					</FormItem>
					<FormItem label="商城价" prop="go8Price" >
						<InputNumber  :min="0" v-model="formData.go8Price" style="width: 200px;"></InputNumber> 元
					</FormItem>
					<FormItem label="货号">
						<Input v-model="formData.productCode" placeholder="(选填)不填系统自动生成" style="width: 200px;"></Input>
					</FormItem>
					<FormItem label="总库存" prop="stock">
						<InputNumber :min="0" v-if="formData.specData.length!=0" disabled v-model="formData.stock" placeholder="有规格时不用填写"   style="width: 200px;"></InputNumber>
						<InputNumber :min="0" v-else-if="formData.specData.length==0" v-model="formData.stock" placeholder="有规格时不用填写"  style="width: 200px;"></InputNumber>
					</FormItem>
				</Form>
			</Card>
			<Card :bordered="false">
				<p slot="title">商品图片</p>
				<Form ref="formNormalPic" :label-width="100">
				<FormItem label="主图" >
				<cupload ref="cuploadAttrPic"></cupload>
				</FormItem>
				<FormItem label="图集" >
				<cupload ref="cuploadAttrImages" multiple ></cupload>
				</FormItem>
				</Form>
			</Card>
			<Card :bordered="false">
				<p slot="title">商品属性</p>
				<Form ref="formNormalAttr" :model="formData" :label-width="100" inline>
				<FormItem :ref="attr.id" v-for="(attr,index) in formData.normalData" :label="attr.name" :key="index"
				:prop="`normalData.${index}.val`" :rules="attr.required == 1 ? (attr.inputType!=3 ? rulelAttr.num : rulelAttr.str) :''">
					<Select v-model="formData.normalData[index].val"  :ref="attr.id ? 'select'+attr.id : ''" v-if="attr.inputType === 1" style="width:176px" filterable>
						<Option v-for="item in attr.values" :value="item.id" :key="item.id">{{ item.value }}</Option>
					</Select>
					<Select v-model="formData.normalData[index].val" :ref="attr.id ? 'select'+attr.id : ''" v-else-if="attr.inputType === 2" style="width:176px" multiple filterable>
						<Option v-for="item in attr.values" :value="item.id" :key="item.id">{{ item.value }}</Option>
					</Select>
					<Input v-model="formData.normalData[index].val" :ref="attr.id ? 'input'+attr.id:''" v-else placeholder="自定义..."
					style="width: 200px" />
					<Button v-if="attr.inputType == 1 || attr.inputType == 2"
					@click="addAttrValue(attr.id,attr.name,attr.type)"
					type="primary" size="small" shape="circle" icon="md-add"></Button>
				</FormItem>
				</Form>
			</Card>
			<Card :bordered="false">
				<p slot="title">包装清单</p>
				<dform ref="dformPackage"></dform>
			</Card>
		</TabPane>

		<TabPane label="商品规格" name="spec">
			<Card :bordered="false">
				<p slot="title">商品规格</p>
				<Form ref="formSpecAttr" :model="formData" :label-width="100">
				<FormItem :ref="attr.id" v-for="(attr,index) in formData.specData" :label="attr.name" :key="index"
				:prop="`specData.${index}.val`" :rules="attr.required == 1 ? rulelAttr.arr : ''">
					<Select @on-change="onSpecSelectChange(option)" label-in-value v-model="formData.specData[index].val" :ref="attr.id ? 'select'+attr.id : ''"  multiple filterable>
						<Option v-for="item in attr.values" :value="item.id" :key="item.id">{{ item.value }}</Option>
					</Select>
					<Button v-if="attr.inputType == 1 || attr.inputType == 2"
					@click="addAttrValue(attr.id,attr.name,attr.type)"
					type="primary" size="small" shape="circle" icon="md-add"></Button>
				</FormItem>
				</Form>
			</Card>
			<Card :bordered="false">
				<p slot="title">规格明细</p>
				<template v-if="skus.rows.length!=0">
					<Row style='font-weight: bold;'>
						<Col v-for="(colum,index) in skus.colums" :key="index" span="4">{{colum}}</Col>
					</Row>
				</template>
				<template v-if="skus.rows.length!=0">
					<Row v-for="(row,index) in skus.rows" :key="index" style="line-height:60px;">
						<template v-for="(attr,index) in row.attrs">
							<Col  span="4">{{attr.value}}</Col>
						</template>
						<Col  span="4"><InputNumber :min="0"  v-model="row.go8Price" size='small' ></InputNumber></Col>
						<Col  span="4"><InputNumber :min="0"  @on-change="onStockChange" v-model="row.stock" size='small' ></InputNumber></Col>
						<Col span="4"><cupload :ref="'cupload'+index" v-model="row.picture"></cupload></Col>
					</Row>
				</template>
			</Card>
		</TabPane>

		<TabPane label="商品详情" name="detail">
			<weditor ref='weditor'></weditor>
		</TabPane>
	</Tabs>
	<div class="footer">
		<Button v-if="tabsValue != 'basic'" @click="tabsValue=='spec' ?tabsValue='basic':tabsValue='spec'" style="">上一步</Button>
		<Button v-if="tabsValue != 'detail'" @click="tabsValue=='basic' ?tabsValue='spec':tabsValue='detail'" style="margin-left: 20px">下一步</Button>
		<Button v-if="tabsValue == 'detail'" type="success" @click="handleSubmit" style="margin-left: 20px">上架</Button>
	</div>

  </div>
</template>
<script>
import weditor from '_c/weditor'
import cupload from '_c/cupload'
import dform from '_c/dynamic-form'
import {getCatalogByPid} from '../../api/catalog.js'
import {getAttrAndValueByCondition, addAttribute, addAttributeValue, getValuesByAttrId} from '../../api/attribute.js'
import {treeToCascader} from '../../libs/object.convert.js'
import {getBrandsByCid} from '../../api/brand.js'
import {addproduct} from '../../api/product.js'
import {toFen} from '../../libs/tools.js'

//记录当前选择的分类对象
let catalogObjs = [];

export default {
  components: {
  	weditor,
  	cupload,
	dform
  },
  data() {
  	return {
		//选择项卡的值
		tabsValue: 'basic',
		//品牌数据
		brandData: [],
  		//分类数据
  		queryCatalogData: [],
		//上传文件
		normalPic: '',
		normalImages: [],
		//skus数据{colums:['颜色','大小','价格','库存'],rows:[{attrs:[{aid:1,name:'颜色',vid:12,value:'白色'},{aid:2,name:'大小',vid:15,value:'大号'}],go8Price:56,stock:120,picture:'/a/b/c.jpg'},{attrs:[{aid:1,name:'颜色',vid:13,value:'黑色'},{aid:2,name:'大小',vid:16,value:'小号'}],go8Price:89,stock:100,picture:'/a/b/d.jpg'}]},
		skus: {colums: [], rows: []},
		//用于属性验证绑定，注意表单modal只能绑定对象，否则验证不起作用
  		formData: {
  			brand: null,
  			price: null,
  			go8Price: null,
  			catalogIDs: [],
  			title: '',
  			subTitle: '',
			productCode: '',
			stock: null,
			picture: '',
			//普通属性数据集，含所有属性值数据
			normalData: [],
			//规格属性数据集，含所有属性值数据
			specData: []
  		},
		//基础数据验证
		ruleBasicValidate: {
			title: [{required: true, message: '名称不能为空', trigger: 'blur'}],
			catalogIDs: [{type: 'array', required: true, message: '分类不能为空', trigger: 'change'}],
			price: {type: 'number', required: true, message: '售价不能为空', trigger: 'blur'},
			go8Price: {type: 'number', required: true, message: '平台价不能为空', trigger: 'blur'},
			stock: {type: 'number', required: true, message: '总库存不能为空', trigger: 'change'}
		},
		//属性数据验证
		rulelAttr: {
			num: [{type: 'number', required: true, message: '该属性值必填', trigger: 'blur'}],
			str: [{required: true, message: '该属性值必填', trigger: 'blur'}],
			arr: [{type: 'array', required: true, message: '该规格值必填', trigger: 'blur'}]
		}
	}
  },
	methods: {
		//级联框弹出时默认加载根分类数据
		onVisibleChange(e) {
			if (e) {
				console.log('cascader load data..............')
				//异步加载分类数据
				getCatalogByPid(0).then(res => {
					let nodes = []
					if (res.data.data) {
						nodes = treeToCascader(res.data.data);
					}
					console.log(nodes)
					this.queryCatalogData = nodes;
				}).catch(err => {
					console.log(err)
				});
			}
		},
		//加载子分类数据
		loadCatalogData(item, callback) {
			console.log('load sub catalogs..........')
			item.loading = true;
			//异步加载分类数据
				getCatalogByPid(item.value).then(res => {
					let nodes = []
					if (item.children) {
						nodes = treeToCascader(res.data.data);
						item.children = nodes;
						item.loading = false;
						callback();
					}
					console.log(nodes)
				}).catch(err => {
					console.log(err)
				});
		},
		//根据分类加载普通属性
		loadAttr(con) {
			getAttrAndValueByCondition(con).then(res => {
				//添加动态属性用于属性验证,2是多选
				for (let i = 0; i < res.data.data.length; i++) {
					if (res.data.data[i].inputType == 2) {
						res.data.data[i].val = []
					} else {
						res.data.data[i].val = ''
					}
				}
				console.log('res.data.data: ' + JSON.stringify(res.data.data))
				if (con.type == 1)	this.formData.normalData = res.data.data
				else if (con.type == 2) this.formData.specData = res.data.data
			}).catch(error => {
				console.log(error);
			})
		},
		//选择分类改变事件
		onCatalogChange(value, selectedData) {
			//保存当前选择的分类对象
			catalogObjs = selectedData;
			//没有选择分类
			console.log('value: ' + value);
			if (value == '') {
				//清空属性数据
				this.formData.normalData = []
				this.formData.specData = []
				//清空品牌数据
				this.brandData = []
				this.formData.brand = ''
				return
			}
			//根据分类加载品牌，属性
			let cids = new String(value).split(',');
			if (cids.length > 0) {
				let cid = cids[cids.length - 1];
				console.log(cid);
				//加载品牌数据
				getBrandsByCid(cid).then(res => {
					this.brandData = res.data.data
				}).catch(err => {
					console.log(err)
				})
				//加载普通属性
				this.loadAttr({'cid': cid, 'type': 1})
				//加载规格
				this.loadAttr({'cid': cid, 'type': 2})
			}
		},
		//添加属性值
		addAttrValue(id, name, type) {
			//追加新的输入框
			console.log("id: " + id)
			//获取自组件
			console.log(this.$refs[id])
			console.log(this.$refs[id][0].$el)
			//保存成功后的回调方法，以便后续使用
			let callback = this.callback_add_attr_value
			//获取新增按钮对象
			let newAdd = this.$refs[id][0].$children[1].$el;
			//隐藏按钮
			newAdd.style.display = "none";
			//创建一个div元素对象
			let div = document.createElement("div")
			div.style.width = "200px"
			div.innerHTML = "<input type='text' placeholder='新的属性值...' style='width:200px' class='ivu-input ivu-input-default' /><input type='button' class='ivu-btn ivu-btn-default' value='保存' />&nbsp;&nbsp;<input type='button' class='ivu-btn ivu-btn-default' value='取消' />"
			div.children[1].onclick = function() {
				let val = div.children[0].value
				console.log(div.children[0].nextElementSibling.tagName)
				if (val == '') {
					if (div.children[0].nextElementSibling.tagName == 'DIV') {
						//提示框已存在
						return
					}
					let tip = document.createElement('div')
					//tip.className = "ivu-form-item-error-tip"
					tip.style.color = 'red'
					tip.style.width = '200px'
					tip.style.margin = 0
					tip.style.padding = 0
					tip.innerText = '属性值不能为空'
					div.insertBefore(tip, div.children[0].nextElementSibling)
					return
				}
				let value = {"attributeId": id, "value": val}
				//添加属性值
				addAttributeValue(value).then(res => {
					if (res.data.status.code == 2000) {
						//调用回调方法,重新绑定数据，并自动选择新添加的数据
						callback(res.data.data.attributeId, res.data.data.id, res.data.data.value, type)
						//删除添加DIV
						newAdd.style.display = "inline"; parentDiv.removeChild(div)
					}
				}).catch(err => {
					console.log(err)
				})
			}
			div.children[2].onclick = function() { newAdd.style.display = "inline"; parentDiv.removeChild(div) }
			//获取当前Vue对象中合适的父元素容器对象，根据页面布局定
			let parentDiv = this.$refs[id][0].$children[0].$el.parentNode;
			//追加div对象
			parentDiv.appendChild(div)
		},
		//添加属性值成功后回调方法
		callback_add_attr_value(aid, vid, val, type) {
			//加载对应的select数据，并选中新增的属性值
			console.log("aid: " + aid + ",vid: " + vid)
			console.log(this.$refs['select' + aid][0])
			let select = this.$refs['select' + aid][0]
			getValuesByAttrId(aid).then(res => {
				if (res.data.status.code == 2000) {
					let data = res.data.data
					console.log("add value call back ............")
					if (type == 1) {
						for (let i = 0; i < this.formData.normalData.length; i++) {
						if (this.formData.normalData[i].id == aid) {
							//替换成新查询的数据
							this.formData.normalData[i].values = data;
							//选择新添加的值,判断是单选或是多选
							if (select.multiple) {
								if (select.values.length == 0) {
									this.formData.normalData[i].val.push(vid)
								} else {
									this.formData.normalData[i].val.push(vid)
								}
							} else {
								this.formData.normalData[i].val = vid
							}
							break
						}
					}
					} else if (type == 2) {
						for (let i = 0; i < this.formData.specData.length; i++) {
							if (this.formData.specData[i].id == aid) {
								//替换成新查询的数据
								this.formData.specData[i].values = data;
								this.formData.specData[i].val.push(vid)
								break
							}
						}
					}
				}
			}).catch(err => {
				console.log(err)
			})
		},
		//规格选择改变事件
		onSpecSelectChange(option) {
			this.skus.colums = []
			this.skus.rows = []
			let datas = this.formData.specData
			for (let i = 0; i < this.formData.specData.length; i++) {
				if (datas[i].val.length != 0) {
					//add colum
					this.skus.colums.push(datas[i].name)
					//当前属性select
					let select = this.$refs['select' + datas[i].id][0]
					//新的rows
					let newRows = []
					//add sku
					for (let j = 0; j < datas[i].val.length; j++) {
						//已经有行了，需要合并属性，产生新的sku
						if (this.skus.rows.length != 0) {
							for (let h = 0; h < this.skus.rows.length; h++) {
								let sku = {attrs: [], go8Price: null, stock: null, picture: null}
								let attr = {aid: 0, name: '', vid: 0, value: null}
								attr.aid = datas[i].id
								attr.name = datas[i].name
								attr.vid = datas[i].val[j]
								//根据vid查找value
								for (let k = 0; k < select.values.length; k++) {
									if (select.values[k].value == datas[i].val[j]) {
										attr.value = select.values[k].label
										break
									}
								}
								//copy old to new
								for (let m = 0; m < this.skus.rows[h].attrs.length; m++) {
									sku.attrs.push(this.skus.rows[h].attrs[m])
								}
								sku.attrs.push(attr)
								newRows.push(sku)
							}
						} else {
							let sku = {attrs: [], go8Price: null, stock: null, picture: null}
							let attr = {aid: 0, name: '', vid: 0, value: null}
							attr.aid = datas[i].id
							attr.name = datas[i].name
							attr.vid = datas[i].val[j]
							//根据vid查找value
							for (let k = 0; k < select.values.length; k++) {
								if (select.values[k].value == datas[i].val[j]) {
									attr.value = select.values[k].label
									break
								}
							}
							//add sku
							sku.attrs.push(attr)
							newRows.push(sku)
						}
					}
					//赋值新的行
					this.skus.rows = newRows
				}
			}
			this.skus.colums.push('价格(元)')
			this.skus.colums.push('库存')
			this.skus.colums.push('规格主图')
		},
		//库存改变事件
		onStockChange(v) {
			let total = 0
			for (let i = 0; i < this.skus.rows.length; i++) {
				total += this.skus.rows[i].stock
			}
			this.formData.stock = total
		},
		//提交表单
		handleSubmit() {
			let formBasicValid = false, formNormalAttrValid = false, formSpecAttrValid = false
			this.$refs['formBasic'].validate((valid) => {
				if (valid) {
					formBasicValid = true
				} else {
					this.$Message.error('商品概要数据不合法!')

				}
			})
			this.$refs['formNormalAttr'].validate((valid) => {
				if (valid) {
					formNormalAttrValid = true
				} else {
					this.$Message.error('商品属性数据不合法!')

				}
			})
			//验证规格formSpecAttr
			this.$refs['formSpecAttr'].validate((valid) => {
				if (valid) {
					formSpecAttrValid = true
				} else {
					this.$Message.error('商品规格数据不完整!')

				}
			})
			//验证详情
			if (this.$refs.weditor.editorContent == '') {
				this.$Message.error('商品详情不能为空!')
				return
			}
			if (formBasicValid && formNormalAttrValid && formSpecAttrValid) {
				//收集整理属性值
				let attrs = {attrs:[],specs:[]}
				for (let i = 0; i < this.formData.normalData.length; i++) {
					let av = {'id': 0, 'name': '', 'values': []}
					av.id = this.formData.normalData[i].id
					av.name = this.formData.normalData[i].name
					console.log(this.$refs['select' + av.id])
					if (this.formData.normalData[i].inputType == 1 || this.formData.normalData[i].inputType == 2) {
						let values = this.$refs['select' + av.id][0].values
						for (let j = 0; j < values.length; j++) {
							av.values[j] = {'id': 0, 'value': ''}
							av.values[j].id = values[j].value
							av.values[j].value = values[j].label
						}
					} else {
						console.log(this.$refs['input' + av.id])
						av.values[0] = {'id': 0, 'value': this.$refs['input' + av.id][0].$el.children[1].value}
					}
					attrs.attrs.push(av)
				}
				//收集所有规格属性值
				for (let i = 0; i < this.formData.specData.length; i++) {
					let av = {'id': 0, 'name': '', 'values': []}
					av.id = this.formData.specData[i].id
					av.name = this.formData.specData[i].name
					console.log(this.$refs['select' + av.id])
					if (this.formData.specData[i].inputType == 1 || this.formData.specData[i].inputType == 2) {
						let values = this.$refs['select' + av.id][0].values
						for (let j = 0; j < values.length; j++) {
							av.values[j] = {'id': 0, 'value': ''}
							av.values[j].id = values[j].value
							av.values[j].value = values[j].label
						}
					} else {
						console.log(this.$refs['input' + av.id])
						av.values[0] = {'id': 0, 'value': this.$refs['input' + av.id][0].$el.children[1].value}
					}
					attrs.specs.push(av)
				}
				console.log(attrs)
				//商品spu
				let product = {}
				product.cid = this.formData.catalogIDs[this.formData.catalogIDs.length - 1]
				product.brandId = this.formData.brand
				product.title = this.formData.title
				product.subTitle = this.formData.subTitle
				product.price = toFen(this.formData.price)
				product.go8Price = toFen(this.formData.go8Price)
				product.productCode = this.formData.productCode
				product.stock = this.formData.stock
				product.status = 1
				product.attributes = JSON.stringify(attrs)
				product.picture = this.normalPic[0] ? this.normalPic[0].url : ''
				let ims = []
				for (let i = 0; i < this.normalImages.length; i++) {
					ims.push(this.normalImages[i].url)
				}
				product.images = ims.join(',')
				//包装清单
				let items = this.$refs['dformPackage'].formDynamic.items
				let packages = []
				for (let i = 0; i < items.length; i++) {
					if (items[i].status && items[i].name != '') {
						packages.push({name: items[i].name, unit: items[i].unit})
					}
				}
				product.packageInfo = JSON.stringify(packages)
				console.log(product)
				//商品详情
				let detail = this.$refs.weditor.editorContent
				console.log(detail)
				//商品规格
				let skus = []
				for (let i = 0; i < this.skus.rows.length; i++) {
					let sku = {attrs: null, picture: null, stock: null, go8Price: null}
					sku.attrs = JSON.stringify(this.skus.rows[i].attrs)
					sku.go8Price = toFen(this.skus.rows[i].go8Price)
					sku.stock = this.skus.rows[i].stock
					sku.picture = this.skus.rows[i].picture
					skus.push(sku)
				}
				console.log(skus)
				//add product
				addproduct({'product': product, 'detail': detail, 'skus': skus})
					.then(res => {
						if (res.data.status.code == 2000) {
							this.$Message.success('添加商品成功');
						}
					}).catch(err => { console.log(err) })
			}
		}
	},
	mounted () {
	   console.log(this.$refs['cuploadAttrPic'])
       this.normalPic = this.$refs['cuploadAttrPic'].uploadList
	   this.normalImages = this.$refs['cuploadAttrImages'].uploadList
    }
}
</script>

<style scoped="scoped">
	div.footer{
    width: 80%;
    padding: 10px;
    background-color: #ffc;
    position: fixed;
    bottom: 0px;
    left: 20%;
    text-align: center;
    z-index: 9999;
}
</style>
